﻿using ECMessageQueue;
using Panuon.UI.Silver;
using System;
using System.Windows;
using System.Threading.Tasks;

namespace FESSC_WORKBENCH
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    public partial class LoginDialog : WindowX
    {
        public LoginDialog()
        {
            InitializeComponent();
        }

        public delegate void dlg();
        private int loginSteps = 0;
        private string errmsg;

        private void BTN_LOGIN_Click(object sender, RoutedEventArgs e)
        {
            if (TB_USER.Text.Trim().Length == 0
                || PB_PASS.Password.Length == 0
                || TB_SERVER.Text.Trim().Length == 0)
            {
                MessageBoxX.Show("登录信息不完整，请补充", "提示", this);
                return;
            }
            try
            {
                ButtonHelper.SetIsWaiting(BTN_LOGIN, true);
                //连接服务器
                void connect()
                {
                    try
                    {
                        if (AppVar.mqworker == null)
                        {
                            AppVar.mqworker = new MQWorker(TB_SERVER.Text,
                                AppVar.opDict, AppVar.log);
                            AppVar.mqworker.startMessageLoop();
                            AppVar.mqclient = AppVar.mqworker.mqclient;
                            AppVar.token = AppVar.mqclient.getClientToken();
                            AppVar.log.Info("Connected to server.");
                            AppVar.log.Info("Client Id[{0}] Token[{1}]", AppVar.mqclient.getId(), AppVar.mqclient.getClientToken());
                        }
                        loginSteps = 1;
                    }
                    catch (Exception)
                    {
                        loginSteps = -1;
                    }
                }

                //注册登录响应的委托方法
                Func<MessageQueue.MQMESSAGE, bool> userLoginRs = delegate (MessageQueue.MQMESSAGE mqm)
                {
                    bool ret = false;
                    try
                    {
                        FESSC_MESSAGE.Msg m = new FESSC_MESSAGE.Msg(mqm.content);
                        string rscode = m.getRsCode();
                        if (rscode == "OK")
                        {
                            ret = true;
                            AppVar.log.Info("登录成功！");
                            Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                new dlg(() =>
                                {
                                    AppVar.uid = TB_USER.Text.Trim();
                                    loginSteps = 2;
                                }));
                        }
                        else
                        {
                            AppVar.log.Info("登录失败：{0}", m.getRsDesc());
                            Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                new dlg(() =>
                                {
                                    errmsg = m.getRsDesc();
                                    loginSteps = -1;
                                    ButtonHelper.SetIsWaiting(BTN_LOGIN, false);
                                }));
                        }
                    }
                    finally
                    {
                        ret = false;
                    }
                    return ret;
                };
                AppVar.opDict.reg("USERLOGIN", userLoginRs);

                //注册用户信息响应的委托方法
                Func<MessageQueue.MQMESSAGE, bool> userInfoRs = delegate (MessageQueue.MQMESSAGE mqm)
                {
                    App.UserInfo uinfo = new App.UserInfo();
                    FESSC_MESSAGE.Msg msg = new FESSC_MESSAGE.Msg(mqm.content);
                    var rscode = msg.getRsCode();
                    if (rscode == "OK")
                    {
                        uinfo.id = msg.getValueByXpath("/rs/userinfo/id");
                        uinfo.name = msg.getValueByXpath("/rs/userinfo/name");
                        uinfo.deptid = int.Parse(msg.getValueByXpath("/rs/userinfo/deptid"));
                        uinfo.deptname = msg.getValueByXpath("/rs/userinfo/deptname");
                        uinfo.groupid = int.Parse(msg.getValueByXpath("/rs/userinfo/groupid"));
                        uinfo.groupname = msg.getValueByXpath("/rs/userinfo/groupname");
                        AppVar.userinfo = uinfo;
                        loginSteps = 3;
                        return true;
                    }
                    else
                    {
                        loginSteps = -1;
                        OP_USERLOGIN.doLogout();
                        errmsg = msg.getRsDesc();
                        return false;
                    }
                };
                AppVar.opDict.reg("USERINFO", userInfoRs);

                //登录过程异步函数
                async void login()
                {
                    Exception ex;
                    var pbox = PendingBox.Show("连接服务器...", "正在登录", false, this);
                    connect();
                    do { await Task.Delay(250); }
                    while (loginSteps == 0);
                    if (loginSteps < 0)
                    {
                        pbox.Close();
                        ex = new Exception("连接服务器失败");
                        throw ex;
                    }
                    //发送登录请求
                    pbox.UpdateMessage("正在请求登录...");
                    OP_USERLOGIN.doLogin(TB_USER.Text, PB_PASS.Password);
                    do { await Task.Delay(250); }
                    while (loginSteps == 1);
                    if (loginSteps < 0)
                    {
                        pbox.Close();
                        ex = new Exception("登录失败：" + errmsg);
                        throw ex;
                    }
                    //请求用户信息
                    pbox.UpdateMessage("获取用户信息...");
                    OP_USERLOGIN.doRequestUserInfo();
                    do { await Task.Delay(250); }
                    while (loginSteps == 2);
                    if (loginSteps < 0)
                    {
                        pbox.Close();
                        ex = new Exception("获取用户信息失败：" + errmsg);
                        throw ex;
                    }
                    pbox.UpdateMessage("登录成功");
                    await Task.Delay(1000);
                    DialogResult = true;
                    pbox.Close();
                    ForceClose();
                }
                login();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                AppVar.log.Error(ex.ToString());
                ButtonHelper.SetIsWaiting(BTN_LOGIN, false);
                loginSteps = 0;
            }
        }

        private void BTN_EXIT_Click(object sender, RoutedEventArgs e)
        {
            ForceClose();
        }
    }
}
